package com.bt.service.impl;


import com.bt.dao.UserMapper;
import com.bt.entity.User;
import com.bt.service.UserService;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(String name, String password) {
        return (User) userMapper.login(name, password);
    }

    @Override
    public List<User> getUserList() {
        return userMapper.selectAll();
    }


    @Override
    public User selectUserById(Integer Id){
        return userMapper.selectByPrimaryKey(Id);
    }
    @Override
    @Transactional
    public int delUser(Integer id){
        return userMapper.deleteByPrimaryKey(id);
    }
    @Override
    @Transactional
    public int updateUser(User user){
        return userMapper.updateByPrimaryKeySelective(user);

    }
    @Override
    @Transactional
    public int addUser(User user){
        return userMapper.insertSelective(user);
    }

    @Override
    public User findByUsername(String username) {
        User user=new User();
        user.setName(username);
        return userMapper.selectOne(user);
    }

    @Override
    @Transactional
    public int saveUser(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public PageInfo<User> findByCondition(String name, String sex, String address, Integer pageNum, Integer pageSize) {
        // 1. 构建动态查询条件
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.hasText(name)) {
            criteria.andLike("name", "%" + name + "%"); // 模糊查询
        }
        if (StringUtils.hasText(sex)) {
            criteria.andEqualTo("sex", sex);// 精确匹配
        }
        if (StringUtils.hasText(address)) {
            criteria.andLike("address", "%" + address + "%");
        }
        // 2. 开启分页
        PageHelper.startPage(pageNum, pageSize);

        // 3. 执行查询
        List<User> users = userMapper.selectByExample(example);

        // 4. 封装分页结果
        return new PageInfo<>(users);

    }
}
